/*
 * Copyright 2008 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.dopdf.document.read.pdf;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.dopdf.document.model.PageDetail;
import org.dopdf.document.model.ResourceDetail;
import org.dopdf.document.read.DocumentReader;
import org.dopdf.io.InputStreamToByteArrayConverter;
import org.dopdf.utils.Constants;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * The class that takes in an input stream and reads the pdf document.  Provides various methods to help process the
 * pdf document.
 *
 * @author Deep Shah
 */
public class PDFDocumentReader implements DocumentReader {

    /**
     * The java util logger reference.
     */
    private static final Logger logger = Logger.getLogger(PDFDocumentReader.class.toString());

    /**
     * The input stream representing the original document.
     */
    private byte[] originalDocument;

    /**
     * The int value representing the total number of pages in the document.
     */
    private int numberOfPages = 0;

    /**
     * The constructor that takes in the pdf input stream to read.
     *
     * @param inputStream the stream that represents a pdf document.
     */
    public PDFDocumentReader(final InputStream inputStream) {
        init(inputStream);
    }

    /**
     * The constructor that takes the pdf bytes as argument.
     *
     * @param bytes the byte array representing the pdf data.
     */
    public PDFDocumentReader(final byte[] bytes) {
        this(new ByteArrayInputStream(bytes));
    }

    /**
     * {@inheritDoc}
     */
    public int getNumberOfPages() {
        return numberOfPages;
    }

    /**
     * {@inheritDoc}
     */
    public ResourceDetail getPageAsImage(final PageDetail pageDetail) {

        PDDocument pdDocument = loadDocument();
        List<PDPage> allPages = pdDocument.getDocumentCatalog().getAllPages();
        PDFPages pdfPages = new PDFPages(allPages);
        try {
            return pdfPages
                    .getPageAsImage(pageDetail.getPageNumber(), pageDetail.getSize());
        } finally {
            pdDocument = null;
            allPages = null;
            pdfPages = null;
        }
    }

    /**
     * {@inheritDoc}
     */
    public ResourceDetail getDocumentAsResource() {
        return new ResourceDetail(originalDocument, Constants.Resource.PDF_CONTENT_TYPE);
    }


    /**
     * The method that will do all the initialization tasks of creating the pdf reader out of the byte array.
     *
     * @param inputStream the input stream that holds the pdf document.
     */
    private void init(final InputStream inputStream) {
        try {
            this.originalDocument = new InputStreamToByteArrayConverter(inputStream).convert();
            numberOfPages = PDDocument.load(new ByteArrayInputStream(this.originalDocument))
                    .getNumberOfPages();
        } catch (final IOException e) {
            logger.log(Level.SEVERE, e.getMessage(), e);
        }
    }

    /**
     * Returns the document pages represented by this current document.
     *
     * @return the document pages represented by the current document.
     */
    private PDDocument loadDocument() {
        try {
            return PDDocument.load(new ByteArrayInputStream(this.originalDocument));
        } catch (IOException e) {
            logger.log(Level.SEVERE, e.getMessage(), e);
            throw new RuntimeException(e);
        }
    }
}
